package com.ruoyi.scene.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.base.domain.vo.BaseBsBdVo;
import com.ruoyi.base.domain.vo.BaseBsProjectVo;
import com.ruoyi.base.mapper.BaseBsBdMapper;
import com.ruoyi.base.mapper.BaseBsProjectMapper;
import com.ruoyi.base.service.IBaseBsBdService;
import com.ruoyi.base.service.IBaseBsProjectService;
import com.ruoyi.cm.domain.vo.CmBaSettleDeductDetailVo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.stereotype.Service;
import com.ruoyi.scene.domain.bo.SceneInspectionIssueBo;
import com.ruoyi.scene.domain.vo.SceneInspectionIssueVo;
import com.ruoyi.scene.domain.SceneInspectionIssue;
import com.ruoyi.scene.mapper.SceneInspectionIssueMapper;
import com.ruoyi.scene.service.ISceneInspectionIssueService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 现场巡查问题Service业务层处理
 *
 * @author llb
 * @date 2024-10-16
 */
@RequiredArgsConstructor
@Service
public class SceneInspectionIssueServiceImpl implements ISceneInspectionIssueService {

    private final SceneInspectionIssueMapper baseMapper;

    private final BaseBsProjectMapper baseBsProjectMapper;

    private final BaseBsBdMapper baseBsBdMapper;

    private final SysUserMapper sysUserMapper;

    private final ISysOssService sysOssService;

    /**
     * 查询现场巡查问题
     */
    @Override
    public SceneInspectionIssueVo queryById(Long id){
        SceneInspectionIssueVo vo = baseMapper.selectVoById(id);
        if (ObjectUtils.isNotEmpty(vo)){
            //项目
            BaseBsProjectVo baseBsProjectVo = baseBsProjectMapper.selectVoById(vo.getProjectId());
            if (ObjectUtils.isNotEmpty(baseBsProjectVo)){
                vo.setProjectName(baseBsProjectVo.getProjectName());
            }
            //标段
            BaseBsBdVo baseBsBdVo = baseBsBdMapper.selectVoById(vo.getBdId());
            if (ObjectUtils.isNotEmpty(baseBsBdVo)){
                vo.setBdName(baseBsBdVo.getName());
            }
            //巡查上报人
            SysUser sysUser = sysUserMapper.selectUserById(Long.valueOf(vo.getXcsbr()));
            if (ObjectUtils.isNotEmpty(sysUser)){
                vo.setXcsbrName(sysUser.getNickName());
            }
            //指派人
            String assignPeopleId = vo.getAssignPeopleId();
            if (ObjectUtils.isNotEmpty(assignPeopleId)){
                String[] split = assignPeopleId.split(",");
                Long[] assignPeopleIds =(Long[]) ConvertUtils.convert(split,Long.class);
                List<Map<String,String>> assignPeopleList = new ArrayList<>();
                Arrays.asList(assignPeopleIds).forEach(t->{
                    Map<String,String> map = new HashMap<>();
                    SysUser user = sysUserMapper.selectUserById(t);
                    if (ObjectUtils.isNotEmpty(user)){
                        map.put("userId",String.valueOf(user.getUserId()));
                        map.put("nickName",user.getNickName());
                        assignPeopleList.add(map);
                    }
                });
                vo.setAssignPeopleList(assignPeopleList);
            }

            //附件
            String fileId = vo.getFileId();
            if (ObjectUtils.isNotEmpty(fileId)){
                String[] split = fileId.split(",");
                Long[] fileIds =(Long[]) ConvertUtils.convert(split,Long.class);
                List<SysOssVo> sysOssVos = sysOssService.listByIds(Arrays.asList(fileIds));
                vo.setOssVoList(sysOssVos);
            }
        }
        return vo;
    }

    /**
     * 查询现场巡查问题列表
     */
    @Override
    public TableDataInfo<SceneInspectionIssueVo> queryPageList(SceneInspectionIssueBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SceneInspectionIssue> lqw = buildQueryWrapper(bo);
        Page<SceneInspectionIssueVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<SceneInspectionIssueVo> records = result.getRecords();
        if(CollUtil.isNotEmpty(records)) {
            records.stream().forEach(e -> {
                //项目
                BaseBsProjectVo baseBsProjectVo = baseBsProjectMapper.selectVoById(e.getProjectId());
                if (ObjectUtils.isNotEmpty(baseBsProjectVo)){
                    e.setProjectName(baseBsProjectVo.getProjectName());
                }
                //标段
                BaseBsBdVo baseBsBdVo = baseBsBdMapper.selectVoById(e.getBdId());
                if (ObjectUtils.isNotEmpty(baseBsBdVo)){
                    e.setBdName(baseBsBdVo.getName());
                }
                //巡查上报人
                SysUser sysUser = sysUserMapper.selectUserById(Long.valueOf(e.getXcsbr()));
                if (ObjectUtils.isNotEmpty(sysUser)){
                    e.setXcsbrName(sysUser.getNickName());
                }
//                //指派人
//                String assignPeopleId = e.getAssignPeopleId();
//                if (ObjectUtils.isNotEmpty(assignPeopleId)){
//                    String[] split = assignPeopleId.split(",");
//                    Long[] assignPeopleIds =(Long[]) ConvertUtils.convert(split,Long.class);
//                    List<Map<String,String>> assignPeopleList = new ArrayList<>();
//                    Arrays.asList(assignPeopleIds).forEach(t->{
//                        Map<String,String> map = new HashMap<>();
//                        SysUser user = sysUserMapper.selectUserById(t);
//                        if (ObjectUtils.isNotEmpty(user)){
//                            map.put("userId",String.valueOf(user.getUserId()));
//                            map.put("nickName",user.getNickName());
//                            assignPeopleList.add(map);
//                        }
//                    });
//                    e.setAssignPeopleList(assignPeopleList);
//                }


                //附件
                String fileId = e.getFileId();
                if (ObjectUtils.isNotEmpty(fileId)){
                    String[] split = fileId.split(",");
                    Long[] fileIds =(Long[]) ConvertUtils.convert(split,Long.class);
                    List<SysOssVo> sysOssVos = sysOssService.listByIds(Arrays.asList(fileIds));
                    e.setOssVoList(sysOssVos);
                }
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询现场巡查问题列表
     */
    @Override
    public List<SceneInspectionIssueVo> queryList(SceneInspectionIssueBo bo) {
        LambdaQueryWrapper<SceneInspectionIssue> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SceneInspectionIssue> buildQueryWrapper(SceneInspectionIssueBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SceneInspectionIssue> lqw = Wrappers.lambdaQuery();
        if(bo.getAllProject()==null||"false".equals(bo.getAllProject())){
            lqw.eq(bo.getProjectId() != null, SceneInspectionIssue::getProjectId, bo.getProjectId());
        }
        lqw.eq(bo.getBdId() != null, SceneInspectionIssue::getBdId, bo.getBdId());
        lqw.eq(StringUtils.isNotBlank(bo.getLczh()), SceneInspectionIssue::getLczh, bo.getLczh());
        lqw.eq(StringUtils.isNotBlank(bo.getWtbt()), SceneInspectionIssue::getWtbt, bo.getWtbt());
        lqw.like(StringUtils.isNotBlank(bo.getCzwt()), SceneInspectionIssue::getCzwt, bo.getCzwt());
        lqw.between(params.get("beginXcsj") != null && params.get("endXcsj") != null,
            SceneInspectionIssue::getXcsj ,params.get("beginXcsj"), params.get("endXcsj"));
        lqw.eq(StringUtils.isNotBlank(bo.getXcsbr()), SceneInspectionIssue::getXcsbr, bo.getXcsbr());
        lqw.eq(StringUtils.isNotBlank(bo.getZgyq()), SceneInspectionIssue::getZgyq, bo.getZgyq());
        lqw.between(params.get("beginZgsx") != null && params.get("endZgsx") != null,
            SceneInspectionIssue::getZgsx ,params.get("beginZgsx"), params.get("endZgsx"));
        lqw.eq(StringUtils.isNotBlank(bo.getFileId()), SceneInspectionIssue::getFileId, bo.getFileId());
        lqw.eq(StringUtils.isNotBlank(bo.getApprovalStatus()), SceneInspectionIssue::getApprovalStatus, bo.getApprovalStatus());
        lqw.orderByDesc(SceneInspectionIssue::getXcsj);
        return lqw;
    }

    /**
     * 新增现场巡查问题
     */
    @Override
    public Boolean insertByBo(SceneInspectionIssueBo bo) {
        SceneInspectionIssue add = BeanUtil.toBean(bo, SceneInspectionIssue.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改现场巡查问题
     */
    @Override
    public Boolean updateByBo(SceneInspectionIssueBo bo) {
        SceneInspectionIssue update = BeanUtil.toBean(bo, SceneInspectionIssue.class);
        validEntityBeforeSave(update);
        //先删除本次修改删掉的附件；
        Set<Long> fileNoOld = bo.getFileNoOld();
        Set<Long> fileNos = bo.getFileNos();
        Set<Long> deleteFiles;
        if(CollUtil.isNotEmpty(fileNoOld)){
            if(CollUtil.isEmpty(fileNos)){
                deleteFiles = fileNoOld;
            } else {
                deleteFiles = fileNoOld.stream().filter(e-> !fileNos.contains(e)).collect(Collectors.toSet());
            }
            if(CollUtil.isNotEmpty(deleteFiles)){
                sysOssService.deleteWithValidByIds(deleteFiles,true);
            }
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SceneInspectionIssue entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除现场巡查问题
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean submit(SceneInspectionIssueBo bo) {
        SceneInspectionIssue update = BeanUtil.toBean(bo, SceneInspectionIssue.class);
        return baseMapper.updateById(update) > 0;
    }
}
